import React, { useState, useEffect } from 'react';
import { AutoComplete, Space, Typography, Avatar, Tag, Spin } from 'antd';
import { ShopOutlined } from '@ant-design/icons';
import { tenantApi } from '@/services/platform/api/tenantApi';
import { PublicTenant } from '@/types';

const { Text } = Typography;

interface SimpleTenantSelectorProps {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  style?: React.CSSProperties;
  disabled?: boolean;
}

const SimpleTenantSelector: React.FC<SimpleTenantSelectorProps> = ({
  value,
  onChange,
  placeholder = "请输入租户代码",
  style,
  disabled = false,
}) => {
  const [options, setOptions] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [,setAllTenants] = useState<PublicTenant[]>([]);

  // 初始化时加载所有公开租户
  useEffect(() => {
    const loadTenants = async () => {
      try {
        const response = await tenantApi.getPublicTenants();
      const tenants = response.data;
        setAllTenants(tenants);
        
        // 根据当前域名自动设置租户
        const hostname = window.location.hostname;
        const subdomain = hostname.split('.')[0];
        
        if (subdomain && subdomain !== 'localhost' && subdomain !== '127' && subdomain !== 'www') {
          const matchedTenant = tenants.find((t: PublicTenant) => t.domain?.startsWith(subdomain));
          if (matchedTenant && !value) {
            onChange?.(matchedTenant.code);
          }
        }
      } catch (error) {
        console.error('加载租户列表失败:', error);
      }
    };

    loadTenants();
  }, []);

  const handleSearch = async (searchText: string) => {
    if (!searchText) {
      setOptions([]);
      return;
    }

    setLoading(true);
    
    try {
      // 使用API搜索租户
      const response = await tenantApi.searchTenants(searchText);
      const searchResults = response.data;
      
      const filtered = searchResults.map((tenant: PublicTenant) => ({
        value: tenant.code,
        label: (
          <Space>
            <Avatar 
              size="small" 
              icon={<ShopOutlined />} 
              src={tenant.logo}
              style={{ backgroundColor: '#1890ff' }} 
            />
            <div>
              <Text strong>{tenant.name}</Text>
              <br />
              <Text type="secondary" style={{ fontSize: 12 }}>
                {tenant.code} • {tenant.domain}
              </Text>
            </div>
            <Tag color={tenant.status === 'active' ? 'green' : 'red'}>
              {tenant.status === 'active' ? '正常' : '不可用'}
            </Tag>
          </Space>
        ),
      }));

      setOptions(filtered);
    } catch (error) {
      console.error('搜索租户失败:', error);
      setOptions([]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <AutoComplete
      value={value}
      onChange={onChange}
      onSearch={handleSearch}
      placeholder={placeholder}
      style={style}
      disabled={disabled}
      options={options}
      notFoundContent={loading ? <Spin size="small" /> : "暂无匹配的租户"}
      filterOption={false} // 禁用内置过滤，使用API搜索
    />
  );
};

export default SimpleTenantSelector;